﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace Gmantis.Controls.DataGrid
{
    public class DataGridCheckBoxConverter : IValueConverter
    {
        // Fields
        private DataGridCheckBoxColumn _column;

        // Methods
        public DataGridCheckBoxConverter(DataGridCheckBoxColumn column)
        {
            this._column = column;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((value != null) && (value.GetType().GetNonNullableType() != typeof(bool)))
            {
                value = this.ConvertBack(value, (targetType.GetNonNullableType() == typeof(bool)) ? targetType : typeof(bool?), parameter, culture);
            }
            if (targetType != typeof(string))
            {
                return value;
            }
            string undefinedText = this._column.UndefinedText;
            if (value != null)
            {
                if (value.Equals(true))
                {
                    return this._column.CheckedText;
                }
                if (value.Equals(false))
                {
                    undefinedText = this._column.UncheckedText;
                }
            }
            return undefinedText;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool flag;
            if (!(value is string))
            {
                return value;
            }
            string str = (value as string).Trim().ToLower();
            if (bool.TryParse(str, out flag))
            {
                return flag;
            }
            if (str == this._column.UndefinedText.ToLower())
            {
                return null;
            }
            if (str == this._column.UncheckedText.ToLower())
            {
                return false;
            }
            return ((str == this._column.CheckedText.ToLower()) || (bool)value);
        }
    }
}
